package server.database;

import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import database.CreateTable;
import database.DataHandler;

/**
 * This class is used to connect to the database, and
 * should be the only class that has this connection.
 * Java DB is the connection type.
 * 
 * @author daniel
 */

public class ConnectionDatabase {

	private static Connection connection;
	private static ResultSet rs = null;
	private static PreparedStatement pstmt = null;
	private static Properties connectionPropeties;

	/* The following variables should be set one time 
	 * related to this project
	 */
	private static String username = null;
	private static String password = null;
	private static String nameDB = "aCalendar";
	private static String driver = "org.apache.derby.jdbc.ClientDriver";
	private static DatabaseType databaseType = DatabaseType.derby;
	private static String serverName;
	private static String portNumber;

	/**
	 * This is the constructor, and establishes the
	 * connection to the database.
	 */
	public static void connect() {
		if(username != null && password != null) {
			connectionPropeties = new Properties();
			connectionPropeties.put("user", username);
			connectionPropeties.put("password", password);
		}

		try {
			Class.forName(driver);

			if(databaseType == DatabaseType.mysql) {
				/* MySQL  eg. "jdbc:mysql://
				 * [subProtocol][databaseName] */
				connection = DriverManager.getConnection
				("jdbc:" + databaseType + "://" + serverName + 
						":" + portNumber + "/", connectionPropeties);

			} else if (databaseType == DatabaseType.derby) {
				/* JavaDB eg "jdbc:derby:[subProtocol:]
				 * [databaseName][;attribute=value]" */
				connection = DriverManager.getConnection(
						"jdbc:" + databaseType + ":" + nameDB + ";create=true");
				//connectionPropeties);
			}

		} catch (SQLException e) {
			System.err.println("SQLException: " + e.getMessage());
			System.err.println("The database is proberly already in use from another instance");
			close();

		} catch (Exception e) {
			System.err.println("Feil i tilkobling " + e);	
			e.printStackTrace();
			close();
		}
		
		CreateTable tables = new CreateTable();
		tables.main(null);
	}
	
	public static Connection getConnection() {
		return connection;
	}

	public static ResultSet getRs() {
		return rs;
	}

	public static PreparedStatement getPstmt() {
		return pstmt;
	}

	public static String getUsername() {
		return username;
	}

	public static void setUsername(String username) {
		ConnectionDatabase.username = username;
	}

	public static String getNameDB() {
		return nameDB;
	}

	public static DatabaseType getDatabaseType() {
		return databaseType;
	}

	/**
	 * Closes the connection to the database.
	 * This method should be called after the connection 
	 * is finished (eg. when the program closes).
	 */
	public static void close() {
		try {
			if(!connection.isClosed()) {
				connection.close();
				DriverManager.getConnection("jdbc:derby:;shutdown=true");
			}
		} catch (Exception e) {
			/* DriverManager.getConnection("jdbc:derby:;shutdown=true");
			 * This line will always throw a SQL exception even though the system will
			 * shut down correctly
			 */
		}
		System.out.println("Tilkobling lukket");
	}

	/**
	 * Saves a simple query to the database
	 * @param s String which is a fully functional
	 * SQL-query which saves something to the database
	 */
	public static int insert(String query) {
		try {
			pstmt = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
			pstmt.executeUpdate();
			rs = pstmt.getGeneratedKeys();
			while(rs.next()) {
				return rs.getInt(1);
			}
		} catch (SQLException e) {
			System.err.println("SQLException: " + e.getMessage());
			//e.printStackTrace();
		}
		return -1;
	}

	public static void update(String query, Statement st) {
		try {
			st.executeUpdate(query);
		} catch (SQLException e) {
			System.err.println("SQLException: " + e.getMessage());
			//e.printStackTrace();
		}
	}

	public static ResultSet get(String query, Statement st) {
		try {
			rs = st.executeQuery(query);
			return rs;
		} catch (SQLException e) {
			System.err.println("SQLException: " + e.getMessage());
			//e.printStackTrace();
		}
		return null;
	}
}
